// pages/propagate/index.ts

import {getRecordSubmitDetails, saveRecord, treeSource} from "../../service/api/api-propagate";
import {fontSizeCalc, handleCode, handleErrCode, isOverNowTime} from "../../utils/util";
import {getApi} from "../../utils/http";

const rules = [{
    name: "sourceId",
    rule: ["required"],
    msg: ["请选择来源"]
}, {
    name: "sourceChannelId",
    rule: ["required"],
    msg: ["请选择渠道"]
}, {
    name: "publishTime",
    rule: ["required"],
    msg: ["请选择日期"]
}, {
    name: "title",
    rule: ["required"],
    msg: ["请输入标题"]
}, {
    name: "remarks",
    rule: [""],
    msg: ["请输入备注"]
}, {
    name: "voucherOriginals",
    rule: ["required"],
    msg: ["凭证不能为空"]
}]

let dateTime;

Page({

    /**
     * 页面的初始数据
     *
     */
    data: {
        recordId: 0,// 纪录id
        record: {
            isCustom: 0,// 是否用户自定义
            publishTime: "",// 发型时间
            remarks: "",// 备注
            sourceChannelId: "",// 资源通道id
            sourceId: "",// 资源名称id
            title: "",// 标题
            voucherOriginals: "",// 凭证内容，这个是数组，为了验证先用字符串
            voucherType: 10,// 凭证类型 10：链接、11：口令，20：文件
            // sourceName: "",// 资源名称
            // sourceChannelName: "",// 资源通道名称
            // reward: 0,// 分数
            // id: 0,
            // createdAccountId: "",// 创建者id
        },// 纪录详情
        access: {} as any,// 当前用户权限
        currentUser: {},// 当前用户信息
        organizations: [],// 当前组织信息
        organization: [],// 选中的
        defaultItemList: [],// 编辑的时候默认选中
        channels: [],// 可选的渠道列表
        options: '',
        drawerVisible: false,// 右侧抽屉是否显示
        drawerChannelVisible: false,// 右侧抽屉是否显示
        voucherLabel: '链接',// 凭证类型
        title: '',// 标题
        remarks: '',// 备注
        voucherOriginals: "",// 凭证
        sourceName: "",// 资源名称
        sourceChannelName: "",// 资源通道名称

        // 凭证类型
        voucherTypeList: [
            {value: 10, label: '链接', check: true},
            {value: 11, label: '口令', check: false},
            {value: 20, label: '图片', check: false},
            // {value: 30, label: '视频',check: false},
            // {value: 40, label: '文件',check: false},
        ],
        imgArr: [],// 上传的图片列表
        imgIdArr: [],// 上传的图片id列表
        serverUrl: `${getApi()}/propagate/record/voucher/save`,// 服务器url
        iconSize: fontSizeCalc(30),
        labelSize: fontSizeCalc(32),
        inputSize: fontSizeCalc(32),
        btnHeight: fontSizeCalc(96) + 'rpx',
        btnLineHeight: fontSizeCalc(70) + 'rpx',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const recordId = options.id || 0;
        let _that = this;
        this.getTreeFun(recordId);
        if (recordId){
            // this.getRecordDetail(recordId);
            wx.setNavigationBarTitle({
                title: '修改记录'
            })
        }
        const {globalData: {access, currentUser}, windowWidth} = getApp();
        let size = windowWidth >= 480 ? 26 : 32;
        this.setData({
            access,
            currentUser,
            recordId,
            options: JSON.stringify(options),
        })
        setTimeout(()=>{
            _that.setData({
                inputSize: fontSizeCalc(size),
            })
        }, 500)
    },

    /**
     * 处理一下凭证类型
     * @param data
     */
    handleVoucherType({voucherType}) {
        switch (voucherType) {
            case 10:
                return '链接'
            case 11:
                return '口令'
            case 20:
                return '图片'
            case 30:
                return '视频'
            case 40:
                return '文件'
            default:
                return ''
        }
    },

    /**
     * 处理一下纪录状态
     * @param data
     */
    handleRecordType({state, isCancel}) {
        return {
            typeName: state === 1 ? '已提交' : (isCancel === 0 ? '正在发布' : '已撤回'),
            bgColor: state === 1 ? '#389E0D' : (isCancel === 0 ? '#91caff' : '#FF814A'),
        }
    },

    /**
     * 通过id获取纪录详情
     * @param id
     */
    async getRecordDetail(id) {
        let _that = this;
        wx.showLoading({
            title: '查询中...'
        })
        // 执行搜索函数
        await getRecordSubmitDetails({id}).then(async (response) => {
            wx.hideLoading();
            const newRecord = response.data || {};
            const {typeName, bgColor} = this.handleRecordType(newRecord);
            newRecord.voucherTypeName = this.handleVoucherType(newRecord);
            newRecord.voucherContent = newRecord.voucherOriginals[0]?.content || '';
            newRecord.bgColor = bgColor;
            newRecord.typeName = typeName;
            let imgIdArr = [],imgArr = [], channels = [], defaultItemList = [];
            if (newRecord.voucherType === 20) {// 图片
                (Array.isArray(newRecord.voucherOriginals) ? newRecord.voucherOriginals : []).forEach(item => {
                    imgIdArr.push(item.id);
                    imgArr.push(item.content);
                })
            }
            if (newRecord.sourceChannelId){// 上次选了渠道
                const curType = (_that.data.organizations || []).find(item => {
                    return item.value == newRecord.sourceType
                }) || {}
                const curSource = curType.children.find(item => {
                    return item.value == newRecord.sourceId
                }) || {}
                channels = curSource?.item.channels || []
            }
            defaultItemList = _that.getDefaultTreeData(newRecord);
            _that.setData({
                record: newRecord,
                imgIdArr,
                imgArr,
                channels,
                title: newRecord.title ?? '',
                remarks: newRecord.remarks ?? '',
                sourceName: newRecord.sourceName ?? '',
                voucherOriginals: newRecord.voucherContent,
                sourceChannelName: newRecord.channelName ?? '',
                sourceChannelId: newRecord.sourceChannelId ?? '',
                // defaultItemList,
            })
        }).catch(error => {
            console.warn(error)
            wx.showToast({
                title: error || '查询失败',
                icon: 'error',
                duration: 1500
            })
            wx.hideLoading();
        }).finally(() => {
            wx.hideLoading();
        })
    },

    /**
     * 获取树结构
     */
    async getTreeFun(id) {
        let _that = this;
        // 执行搜索函数
        await treeSource({
            filter: 1,
        }).then(async (res) => {
            if (res?.data) {
                _that.setData({
                    organizations: Array.isArray(res.data) ? this.readyTreeData(res.data) : []
                })
                id &&  _that.getRecordDetail(id);
            }
        })
    },

    /**
     * 预备Tree结构数据
     * @param data
     */
    readyTreeData(data: PropagateSettingData.SourceTree[]): any {
        let treeData = [];
        if (data) {
            data.forEach((val) => {
                const disabled = val.isFolder === 1 && !val.children?.length;// 是否能选
                val.disabled = disabled;
                treeData.push({
                    text: val.name,
                    value: val.id,
                    item: val,
                    children: this.readyTreeData(val.children as PropagateSettingData.SourceTree[]),
                    disabled
                    // icon: val.isFolder === 0 ? 1 : 0,
                });
            });
        }
        return treeData;
    },

    /**
     * 获取上次选的Tree结构数据
     */
    getDefaultTreeData(newRecord): any {
        let targetList = []
        const curType = (this.data.organizations || []).find(item => {
            return item.value == newRecord.sourceType
        })
        if (curType) {
            const newData = {...curType};
            delete newData.item;
            delete newData.children;
            targetList[0] = newData
            const curSource = curType.children.find(item => {
                return item.value == newRecord.sourceId
            })
            if (curSource){
                const newData1 = {...curSource};
                delete newData1.item;
                delete newData1.children;
                targetList[1] = newData1
                const curChanel = curSource.children.find(item => {
                    return item.id == newRecord.sourceChannelId
                })
                if (curChanel){
                    const newData2 = {...curSource};
                    delete newData2.item;
                    delete newData2.children;
                    targetList[2] = {
                        text: newData2.channelName,
                        value: newData2.id
                    }
                }
            }
        }
        return targetList
    },

    /**
     * 联级选择 修改
     */
    cascadeChange(res: { detail: any; }) {
        const detail = res?.detail;
        // console.log(detail);
        this.setData({
            organization: detail,
            ['record.sourceChannelId']: '',
            sourceChannelName: '',
        })
    },

    /**
     * 输入框发生变化
     */
    inputChange(res: { detail: any }) {
        // this.setData({
        //     ['record.voucherOriginals']: res.detail,
        // })
    },

    /**
     * 单选框发生变化
     */
    voucherRadioChange(res: { detail: any }) {
        const {voucherTypeList, record: {voucherType}} = this.data;
        // 赋值一下选中的
        // voucherTypeList.forEach(item => {
        //     item.check = item.value === voucherType
        // })
        const {label} = voucherTypeList.find(item => item.value == voucherType) || {};

        this.setData({
            drawerVisible: false,
            voucherTypeList,
            voucherLabel: label,
            ['record.voucherType']: Number(res.detail?.value) || 0,
        })
    },

    /**
     * 单选框发生变化
     */
    drawerRadioChange(res: { detail: any }) {
        const id = res.detail?.value;
        const {channelName} = this.data.channels.find(item => item.id == id) || {};
        this.setData({
            drawerChannelVisible: false,
            ['record.sourceChannelId']: id,
            sourceChannelName: channelName || '',
        })
    },

    /**
     * 显示侧面抽屉
     */
    showDrawer() {
        this.setData({
            drawerVisible: true
        })
    },

    /**
     * 关闭抽屉
     */
    closeDrawer(e) {
        // console.log(e);
        const {organization} = this.data;
        this.setData({
            drawerVisible: false,
            ['record.sourceId']: organization.value,
            ['record.sourceChannelId']: "",// 重置一下
            sourceName: organization.text,
            sourceChannelName: "",// 重置一下
            channels: (organization.item?.channels || []).map(item => {
                return {
                    ...item,
                    check: false,
                }
            }),
        })
    },

    /**
     * 显示侧面抽屉
     */
    showChannelDrawer() {
        const {channels, record: {sourceChannelId}} = this.data;
        // 赋值一下选中的
        channels.forEach(item => {
            item.check = item.id == sourceChannelId
        })
        this.setData({
            channels,
            drawerChannelVisible: true,
        })
    },

    /**
     * 关闭抽屉
     */
    closeChannelDrawer(e: any) {
        this.setData({
            drawerChannelVisible: false,
        })
    },

    /**
     * 显示时间选择
     */
    showDateTime() {
        dateTime.show();
    },

    /**
     * 时间确定
     * {year: Number,month: Number,result: String}
     */
    timeConfirm({detail}) {
        //选择的结果
        this.setData({
            ['record.publishTime']: detail.result,
        })
    },

    /**
     * 时间取消
     */
    timeCancel() {
        this.setData({
            drawerVisible: false
        })
    },

    /**
     * 提交验证
     */
    submit() {
        const {
            record: {
                isCustom,
                publishTime,
                sourceChannelId,
                sourceId,
                voucherType,
            }, title, remarks, voucherOriginals, channels = []
        } = this.data;
        let formData = {
            isCustom,// 是否用户自定义
            publishTime,// 发型时间
            remarks,// 备注
            sourceChannelId,// 资源通道id
            sourceId,// 资源名称id
            title,// 标题
            voucherOriginals,// 凭证内容，这个是数组，为了验证先用字符串
            voucherType: Number(voucherType),// 凭证类型 10：链接、11：口令，20：文件
        };
        if (isOverNowTime(formData.publishTime)) {
            return
        }
        if (Number(voucherType) === 20) {// 如果是图片，为了校验通过，默认添加一些数据进去
            formData.voucherOriginals = this.data.imgIdArr.length ? 'imgIdArr': '';
        }
        // if (channels.length) {// 有渠道
        //     rules.splice(1, 0, {
        //         name: "sourceChannelId",
        //         rule: ["required"],
        //         msg: ["请选择渠道"]
        //     })
        // } else {
        //     const index = rules.findIndex(item => item.name === "sourceChannelId");
        //     index >= 0 && rules.splice(index, 1); // 删掉
        // }

        this.selectComponent("#form").validate(formData, rules).then(res => {
            this.saveFun(formData)
        }).catch(errors => {
            console.log(errors)
        })
    },

    /**
     * 保存函数
     */
    async saveFun(params) {
        let record = params, {currentUser, recordId, imgIdArr = []} = this.data;
        // record.createdAccountId = currentUser.id;
        if (!record.publishTime.includes('00:00')) {
            record.publishTime += ' 00:00:00';
        }
        record.voucherOriginals = [record.voucherOriginals];// 变成数组
        if (record.voucherType === 20) {// 图片
            record.voucherOriginals = [...imgIdArr];
        }
        await saveRecord(record).then(async (res) => {
            if (res?.code === 0) {
                handleCode(res, recordId ? '修改成功' : '新增成功');
                setTimeout(() => {
                    wx.navigateBack({
                        delta: 1
                    })// 回到上一个界面
                }, 1000)
            } else {
                handleErrCode()
            }
        }).catch(e => {
            handleErrCode(e)
        })
    },

    /**
     * 图片上传结果
     *
     * status: Number //上传状态 1-成功 2-上传中 3-失败
     * imgArr: Array //图片信息
     * idList: Array //图片id列表
     * params: params //自定义参数
     * manual: false //是否手动上传
     *
     }
     */
    imgUploadResultFun({detail: {status, imgArr, idList = [], params, manual}}) {
        this.setData({
            imgIdArr: idList
        })
    },

    /**
     * 图片删除
     * index: Number //删除的下表
     * params: params //自定义参数
     */
    imgUploadRemoveFun(e:any) {
        const {index,params} = e.detail || {};
        let imgIdArr = this.data.imgIdArr;
        imgIdArr.splice(index,1);
        this.setData({
            imgIdArr
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        dateTime = this.selectComponent("#dateTime")
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    taskExecuteShareFun() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
    }
})